import com.adobe.serialization.json.JSON;

import mx.collections.ArrayCollection;
import mx.collections.Sort;
import mx.collections.SortField;
import mx.controls.Alert;
import mx.rpc.events.FaultEvent;
import mx.rpc.events.ResultEvent;

private var config:Object;
private var modelConfig:Object;
private var currLevel:String;
private var signalTotalCount:int=new int();
private var tmpsignalTotalCount:int;
[Bindable]
public var modelPartList:ArrayCollection;

[Bindable]
private var aTemp:Array= new Array();


private function handle_config_files(event:ResultEvent):void {
	
	if (event.target.url == "arabidopsis_map.json") {
				
		config = (JSON.decode(String(event.result)));
		modelConfig= (JSON.decode(String(event.result)));
		

		modelConfig = (JSON.decode(String(event.result)));
		//	rotateModel = modelConfig.settings.rotate_model;
		loadPolFile(modelConfig.settings.webservice.policy_file);
		//defaultColour = new ColorMaterial(modelConfig.settings.default_colour, 1, true);
		if (modelConfig.settings.example == null) {
			///	example.enabled = false;
		} else {
			//example.enabled = true;
		}
		
		//loadModel(modelConfig.settings.model_path);
		currLevel = modelConfig.settings.name;
		
		//initKeyFunctions()
	}
	//submitAGI();
}

/**
 * Retrieves the crossdomain file for the web-service policy file.
 */
private function loadPolFile(url:String):void {
	
	Security.loadPolicyFile(url);
}

private function submitAGI():void{
	//modelPartList=new ArrayCollection();
	aTemp= new Array();
	signalTotalCount=new int();
	var base:String = modelConfig.settings.webservice.src + "?primaryGene=" + input_AGI.text;
	
	//var dparray:ArrayCollection;
	for (var objectName:String in modelConfig.modelmap) {
		// The first item in the list is the tissue name, start from 1 and down
		var samplePos:int = 1
		
		
		for (samplePos; samplePos < modelConfig.modelmap[objectName].length; samplePos++) {
			serve_getExpressionData.url = base + "&sample=" + modelConfig.modelmap[objectName][samplePos].toLowerCase();
			//tmpsignalTotalCount=modelConfig.modelmap[objectName].length;
			//newstraing=modelConfig.modelmap[objectName][samplePos].toLowerCase();
			serve_getExpressionData.send();
			signalTotalCount++;
			
			//if( signalTotalCount == tmpsignalTotalCount-1){
				//trace('signalTotalCount '+signalTotalCount.toString());
				
				
			//}
			
			//dparray.addItem(modelConfig.modelmap[objectName][samplePos].toLowerCase());
		}
	
		//relativeComboBox.dataProvider=dparray;
	}
	//for(var i:int=0;i<aTemp.length;i++){
		//modelPartList.addItem({label: aTemp[i]});
//	aTemp.sort();

	//}
	

		//modelPartList.addItem({label: listLabels[label], data: listData[listLabels[label]]});
		//.addItem(
		
	//	aTemp1= new Array();
		//Alert.show(modelPartList.length.toString());
	
		//if(aTemp.length==signalTotalCount  ){
			//trace('tm2');
	//aTemp.sort();
				//modelPartList=new ArrayCollection(aTemp);
				//myChart.dataProvider=modelPartList;
		//}
	
		aTemp= new Array();
		
}

private function calsignal():void{
	modelPartList=new ArrayCollection();
	for (var objectName:String in modelConfig.modelmap) {
	var samplePos:int = 1
	for (samplePos; samplePos < modelConfig.modelmap[objectName].length; samplePos++) {
		var val:Number = aTemp[modelConfig.modelmap[objectName][samplePos].toLowerCase()];
		modelPartList[objectName].samples.push(val);
	}}
	}
private function sum(arr:Array):Number {
	var result:Number = 0;
	for (var i:int = 0; i < arr.length; i++) {
		result += arr[i];
	}
	return result;
}
private function average(arr:Array):Number {
	return (sum(arr) / arr.length);
}


private var expall:Number=0;
private var averageArray:Array=new Array();
private var expaveragevalue:Number=0;

private function expressionDataResult(event:ResultEvent):Boolean {
	
/*	var exprData1:Object = JSON.decode(String(event.result.toString()));
	for (var names:String in exprData1) {
		//aTemp[name] = exprData[name];
		expall=exprData1[names];
		
		averageArray.push(exprData1[names]);
		//if(aTemp.length==signalTotalCount  ){
			//expaveragevalue	=expall;
			
		//}
		
	}*/
	
/*		expall=expall;
	if(averageArray.length==signalTotalCount  ){
		expaveragevalue=expall;
		//Alert.show(expaveragevalue.toString());
	}
*/
	

	expaveragevalue=0;
	var exprData:Object = JSON.decode(String(event.result.toString()));
	//Alert.show(exprData.name[0].toString());
	for (var name:String in exprData) {
		//aTemp[name] = exprData[name];
		trace(exprData[name]);	
		
		expall+=parseInt(exprData[name]);
		aTemp.push({data:exprData[name],label:name,mean:expaveragevalue});
		
		if(aTemp.length==signalTotalCount){
			expaveragevalue=expall/signalTotalCount;
			expall=0;
		}
		trace("Average:" + expaveragevalue);
		if(expaveragevalue!=0){
		Alert.show("Average:" +expaveragevalue.toString());
		expaveragevalue=0;
		
		}
		
		//
		//Alert.show(aTemp.toString());
		//for(var i:int=0;i<aTemp.length;i++){
			
		//}
		//expall=sum(exprData[name]);
		//average(aTemp);
		
	}
	expaveragevalue=0;

	//expall=0;
	//
	/*for(var i:Number = 0; i < aTemp.length; i++) {
		trace("Data:" + aTemp[i].data);
			//averageArray.push();
		//	var tmpint:Number=0;
			expaveragevalue=aTemp[i].data;
		expall+=expaveragevalue;
		trace("Sum:" + expall/21);
	}*/
	
	
/*	averageArray=aTemp;
	for(var i:int;i<averageArray.length;i++){
		if(averageArray.length>=signalTotalCount){
			expall=averageArray[i].data;
		Alert.show(expall.toString());}
	}*/

	/*for (var names:String in exprData1) {
		//aTemp[name] = exprData[name];
		expall+=exprData[name];
	//	averageArray.push(exprData1[names]);
	//	expaveragevalue=average(averageArray);	
		//exparray.push({label:names});
		//aTemp.push({data:exprData[name],label:name,mean:expaveragevalue/21});
		Alert.show(expaveragevalue.toString());
		//average(aTemp);
		
	}*/
	
	//for (var name:String in exprData) {
	//averageArray.push(exprData[name]);
	//}
	/*for(var i:int=0;i<aTemp.length;i++){
		
		averageArray.push(exprData[i]);
	}*/
	//averageArray.push(expall);
	//expaveragevalue+=expall;
	//if(aTemp.length==signalTotalCount  ){
//average(averageArray);
	//Alert.show(expaveragevalue.toString());
	
	//expaveragevalue=new int();
	//}
//	
	//calsignal();
	//trace("name"+exprData[value]);
	//Alert.show(signalTotalCount.toString());
	//if(signalTotalCount==tmpsignalTotalCount){
	//modelPartList=new ArrayCollection(aTemp);
	//}
	//if(aTemp.length==tmpsignalTotalCount){
	//	Alert.show(tmpsignalTotalCount.toString());
	trace('tmpsignalTotalCount '+tmpsignalTotalCount+' aTemp '+aTemp.length+' signalTotalCount '+signalTotalCount);
	//create the sort object

	//aTemp=new Array();
	//}
	if(aTemp.length==signalTotalCount  ){
	//aTemp.sort();
///		aTemp.push({mean:33});
		modelPartList=new ArrayCollection(aTemp);
		sortCollection(modelPartList);
		//aTemp=new Array();
		//myChart.dataProvider=modelPartList;
		//aTemp=new Array();
		//trace('tm');
	}
	//
	//aTemp=new Array();
	//modelPartLis(aTemp);
	
return true;
}

private function sortCollection(arrayCollection : ArrayCollection) : void
{
	//Create the sort field
	var dataSortField:SortField = new SortField();
	
	//name of the field of the object on which you wish to sort the Collection
	dataSortField.name = "label";
	dataSortField.caseInsensitive = true;
	
	/*
	If you wish to perform numeric sort then set:
	dataSortField.numeric = true;
	*/
	
	//create the sort object
	var dataSort:Sort = new Sort();
	dataSort.fields = [dataSortField];
	
	arrayCollection.sort = dataSort;
	//refresh the collection to sort
	arrayCollection.refresh();
	
	
}


/**
 * Handle failed HTTPService component requests.
 */
private function expressionDataResultFault(event:FaultEvent):Boolean {
	//Alert.show(event.fault.content.toString());
	
	//changeStatus("There was an error loading webservice data, please try again.");
	return true;
}